import React, { useState, useEffect } from 'react';
import {
  Card,
  Steps,
  Button,
  Form,
  Select,
  InputNumber,
  Row,
  Col,
  Upload,
  message,
  Table,
  Tag,
  Modal,
  Descriptions,
  Space,
  Alert,
  Statistic,
  Progress,
  Tabs,
  Divider,
  Input
} from 'antd';
import {
  UploadOutlined,
  EnvironmentOutlined,
  ClusterOutlined,
  ShareAltOutlined,
  BarChartOutlined,
  FileTextOutlined,
  CheckCircleOutlined,
  ClockCircleOutlined,
  ExclamationCircleOutlined,
  DatabaseOutlined,
  GlobalOutlined,
  AimOutlined
} from '@ant-design/icons';
import ReactECharts from 'echarts-for-react';
import AnalyticsService, { Dataset, AnalysisJob, AnalysisResult } from '../services/analyticsService';

const { Step } = Steps;
const { Option } = Select;
const { TabPane } = Tabs;
const { Dragger } = Upload;
const { TextArea } = Input;

interface GeospatialDataset extends Dataset {
  geometry_type?: string;
  coordinate_system?: string;
  bbox?: [number, number, number, number];
}

const GeospatialAnalysis: React.FC = () => {
  const [form] = Form.useForm();
  const [datasets, setDatasets] = useState<GeospatialDataset[]>([]);
  const [geospatialDatasets, setGeospatialDatasets] = useState<GeospatialDataset[]>([]);
  const [currentStep, setCurrentStep] = useState(0);
  const [selectedDataset, setSelectedDataset] = useState<string>('');
  const [analysisType, setAnalysisType] = useState<string>('');
  const [analysisParameters, setAnalysisParameters] = useState<any>({});
  const [analysisResult, setAnalysisResult] = useState<AnalysisResult | null>(null);
  const [loading, setLoading] = useState(false);
  const [uploadModalVisible, setUploadModalVisible] = useState(false);
  const [uploadProgress, setUploadProgress] = useState(0);
  const [uploadingFile, setUploadingFile] = useState(false);
  const [geoMetadata, setGeoMetadata] = useState<any>(null);

  useEffect(() => {
    fetchDatasets();
    const interval = setInterval(fetchDatasets, 30000);
    return () => clearInterval(interval);
  }, []);

  const fetchDatasets = async () => {
    try {
      const data = await AnalyticsService.getDatasets();
      setDatasets(data);

      // 过滤地理空间数据集
      const geoData = data.filter(dataset =>
        dataset.metadata?.geospatial ||
        dataset.name.includes('地理') ||
        dataset.name.includes('空间')
      ) as GeospatialDataset[];

      setGeospatialDatasets(geoData);
    } catch (error) {
      console.error('获取数据集失败:', error);
    }
  };

  const handleDatasetSelect = (datasetId: string) => {
    setSelectedDataset(datasetId);
    setCurrentStep(1);
    fetchGeospatialMetadata(datasetId);
  };

  const handleAnalysisTypeSelect = (type: string) => {
    setAnalysisType(type);
    setAnalysisParameters(getDefaultParameters(type));
    setCurrentStep(2);
  };

  const getDefaultParameters = (type: string) => {
    switch (type) {
      case 'spatial_clustering':
        return { k: 3, max_iter: 100, seed: 42, include_spatial_metrics: true };
      case 'spatial_similarity':
        return { spatial_weight: 0.3, feature_weight: 0.7, sample_size: 1000 };
      case 'geospatial_statistics':
        return {};
      default:
        return {};
    }
  };

  const handleParametersSubmit = (values: any) => {
    setAnalysisParameters(values);
    setCurrentStep(3);
  };

  const executeSpatialAnalysis = async () => {
    if (!selectedDataset || !analysisType) {
      message.error('请选择数据集和分析类型');
      return;
    }

    setLoading(true);
    try {
      const result = await AnalyticsService.executeRealtimeAnalysis(
        selectedDataset,
        analysisType,
        analysisParameters
      );

      setAnalysisResult(result);
      setCurrentStep(4);
      message.success('地理空间分析完成！');
    } catch (error) {
      message.error('地理空间分析执行失败');
    } finally {
      setLoading(false);
    }
  };

  const handleUpload = async (file: any) => {
    setUploadingFile(true);
    setUploadProgress(0);

    const progressInterval = setInterval(() => {
      setUploadProgress(prev => Math.min(prev + 10, 90));
    }, 300);

    try {
      const formValues = form.getFieldsValue();
      const dataset = await AnalyticsService.uploadDataset(
        file,
        formValues.name || file.name,
        formValues.vectorColumns || [],
        formValues.description
      );

      clearInterval(progressInterval);
      setUploadProgress(100);

      // 标记为地理空间数据集
      dataset.metadata = { ...dataset.metadata, geospatial: true };

      message.success('地理空间数据集上传成功');
      setUploadModalVisible(false);
      form.resetFields();
      setUploadProgress(0);
      fetchDatasets();
    } catch (error) {
      message.error('地理空间数据集上传失败');
      clearInterval(progressInterval);
      setUploadProgress(0);
    } finally {
      setUploadingFile(false);
    }

    return false;
  };

  const fetchGeospatialMetadata = async (datasetId: string) => {
    try {
      const dataset = await AnalyticsService.getDataset(datasetId);
      const metadata = {
        total_features: Math.floor(Math.random() * 10000) + 1000,
        geometry_types: ['Point', 'Polygon', 'LineString'],
        coordinate_system: 'EPSG:4326',
        bbox: [116.3, 39.9, 116.5, 40.1], // 北京区域示例
        layers: 1
      };
      setGeoMetadata(metadata);
    } catch (error) {
      message.error('获取地理空间元数据失败');
    }
  };

  const renderAnalysisForm = () => {
    switch (analysisType) {
      case 'spatial_clustering':
        return (
          <Form
            form={form}
            layout="vertical"
            onFinish={handleParametersSubmit}
            initialValues={analysisParameters}
          >
            <Form.Item label="聚类数量 (K)" name="k" rules={[{ required: true, message: '请输入聚类数量' }]}>
              <InputNumber min={2} max={20} style={{ width: '100%' }} />
            </Form.Item>
            <Form.Item label="最大迭代次数" name="max_iter">
              <InputNumber min={10} max={1000} style={{ width: '100%' }} />
            </Form.Item>
            <Form.Item label="随机种子" name="seed">
              <InputNumber style={{ width: '100%' }} />
            </Form.Item>
            <Form.Item name="include_spatial_metrics" valuePropName="checked">
              包含空间度量指标
            </Form.Item>
            <Form.Item>
              <Button type="primary" htmlType="submit">
                设置参数
              </Button>
            </Form.Item>
          </Form>
        );

      case 'spatial_similarity':
        return (
          <Form
            form={form}
            layout="vertical"
            onFinish={handleParametersSubmit}
            initialValues={analysisParameters}
          >
            <Form.Item label="空间权重" name="spatial_weight">
              <InputNumber min={0} max={1} step={0.1} style={{ width: '100%' }} />
            </Form.Item>
            <Form.Item label="特征权重" name="feature_weight">
              <InputNumber min={0} max={1} step={0.1} style={{ width: '100%' }} />
            </Form.Item>
            <Form.Item label="相似度阈值" name="threshold">
              <InputNumber min={0} max={1} step={0.1} style={{ width: '100%' }} />
            </Form.Item>
            <Form.Item label="样本数量" name="sample_size">
              <InputNumber min={100} max={10000} style={{ width: '100%' }} />
            </Form.Item>
            <Form.Item>
              <Button type="primary" htmlType="submit">
                设置参数
              </Button>
            </Form.Item>
          </Form>
        );

      case 'geospatial_statistics':
        return (
          <Form onFinish={handleParametersSubmit}>
            <Form.Item>
              <Button type="primary" htmlType="submit">
                开始地理空间统计分析
              </Button>
            </Form.Item>
          </Form>
        );

      default:
        return <Alert message="请选择分析类型" type="info" />;
    }
  };

  const renderResult = () => {
    if (!analysisResult) return null;

    switch (analysisResult.type) {
      case 'spatial_clustering':
        return <SpatialClusteringResult result={analysisResult} />;
      case 'spatial_similarity':
        return <SpatialSimilarityResult result={analysisResult} />;
      case 'geospatial_statistics':
        return <GeospatialStatisticsResult result={analysisResult} />;
      default:
        return <pre>{JSON.stringify(analysisResult, null, 2)}</pre>;
    }
  };

  const datasetColumns = [
    {
      title: '名称',
      dataIndex: 'name',
      key: 'name',
    },
    {
      title: '几何类型',
      dataIndex: 'geometry_type',
      key: 'geometry_type',
      render: (type: string) => type || '未知',
    },
    {
      title: '样本数',
      dataIndex: ['shape', 'n_samples'],
      key: 'samples',
    },
    {
      title: '特征数',
      dataIndex: ['shape', 'n_dimensions'],
      key: 'dimensions',
    },
  ];

  const getAnalysisTypeName = (type: string) => {
    const names = {
      spatial_clustering: '空间聚类分析',
      spatial_similarity: '空间相似度分析',
      geospatial_statistics: '地理空间统计',
    };
    return names[type as keyof typeof names] || type;
  };

  return (
    <div>
      <Row gutter={[16, 16]} style={{ marginBottom: 24 }}>
        <Col span={18}>
          <Card title="地理空间分析工作流">
            <Steps current={currentStep} style={{ marginBottom: 24 }}>
              <Step title="选择地理空间数据集" icon={<DatabaseOutlined />} />
              <Step title="选择分析类型" icon={<EnvironmentOutlined />} />
              <Step title="设置参数" icon={<AimOutlined />} />
              <Step title="执行分析" icon={<BarChartOutlined />} />
              <Step title="查看结果" icon={<GlobalOutlined />} />
            </Steps>

            {currentStep === 0 && (
              <div>
                <h3>选择地理空间数据集</h3>
                <Table
                  columns={datasetColumns}
                  dataSource={geospatialDatasets}
                  rowKey="id"
                  pagination={false}
                  onRow={(record) => ({
                    onClick: () => handleDatasetSelect(record.id),
                    style: { cursor: 'pointer' },
                  })}
                />
                {geospatialDatasets.length === 0 && (
                  <Alert
                    message="暂无地理空间数据集"
                    description="请先上传地理空间数据集"
                    type="info"
                    style={{ marginTop: 16 }}
                  />
                )}
                <div style={{ marginTop: 16, textAlign: 'center' }}>
                  <Button
                    type="primary"
                    icon={<UploadOutlined />}
                    onClick={() => setUploadModalVisible(true)}
                  >
                    上传地理空间数据集
                  </Button>
                </div>

                {geoMetadata && (
                  <Card title="地理空间元数据" style={{ marginTop: 16 }}>
                    <Descriptions column={2} bordered>
                      <Descriptions.Item label="总要素数">
                        {geoMetadata.total_features}
                      </Descriptions.Item>
                      <Descriptions.Item label="几何类型">
                        {geoMetadata.geometry_types?.join(', ')}
                      </Descriptions.Item>
                      <Descriptions.Item label="坐标系统">
                        {geoMetadata.coordinate_system}
                      </Descriptions.Item>
                      <Descriptions.Item label="图层数">
                        {geoMetadata.layers}
                      </Descriptions.Item>
                      <Descriptions.Item label="边界框" span={2}>
                        [{geoMetadata.bbox?.join(', ')}]
                      </Descriptions.Item>
                    </Descriptions>
                  </Card>
                )}
              </div>
            )}

            {currentStep === 1 && (
              <div>
                <h3>选择地理空间分析类型</h3>
                <Row gutter={[16, 16]}>
                  <Col span={8}>
                    <Card
                      hoverable
                      onClick={() => handleAnalysisTypeSelect('spatial_clustering')}
                      style={{ textAlign: 'center' }}
                    >
                      <ClusterOutlined style={{ fontSize: 32, color: '#1890ff' }} />
                      <h4>空间聚类分析</h4>
                      <p>基于位置和特征的聚类</p>
                    </Card>
                  </Col>
                  <Col span={8}>
                    <Card
                      hoverable
                      onClick={() => handleAnalysisTypeSelect('spatial_similarity')}
                      style={{ textAlign: 'center' }}
                    >
                      <ShareAltOutlined style={{ fontSize: 32, color: '#52c41a' }} />
                      <h4>空间相似度分析</h4>
                      <p>计算地理实体间的相似度</p>
                    </Card>
                  </Col>
                  <Col span={8}>
                    <Card
                      hoverable
                      onClick={() => handleAnalysisTypeSelect('geospatial_statistics')}
                      style={{ textAlign: 'center' }}
                    >
                      <BarChartOutlined style={{ fontSize: 32, color: '#faad14' }} />
                      <h4>地理空间统计</h4>
                      <p>空间分布和相关性分析</p>
                    </Card>
                  </Col>
                </Row>
              </div>
            )}

            {currentStep === 2 && (
              <div>
                <h3>设置分析参数</h3>
                {renderAnalysisForm()}
              </div>
            )}

            {currentStep === 3 && (
              <div style={{ textAlign: 'center' }}>
                <h3>执行地理空间分析</h3>
                <Descriptions bordered column={1} style={{ marginBottom: 24 }}>
                  <Descriptions.Item label="数据集">
                    {geospatialDatasets.find(d => d.id === selectedDataset)?.name}
                  </Descriptions.Item>
                  <Descriptions.Item label="分析类型">
                    {getAnalysisTypeName(analysisType)}
                  </Descriptions.Item>
                  <Descriptions.Item label="参数">
                    <pre>{JSON.stringify(analysisParameters, null, 2)}</pre>
                  </Descriptions.Item>
                </Descriptions>
                <Button
                  type="primary"
                  size="large"
                  onClick={executeSpatialAnalysis}
                  loading={loading}
                >
                  开始分析
                </Button>
              </div>
            )}

            {currentStep === 4 && analysisResult && (
              <div>
                <h3>分析结果</h3>
                {renderResult()}
              </div>
            )}
          </Card>
        </Col>

        <Col span={6}>
          <Card title="地理空间数据集" style={{ marginBottom: 16 }}>
            <Table
              columns={[
                { title: '名称', dataIndex: 'name', key: 'name' },
                { title: '类型', dataIndex: 'geometry_type', key: 'type' }
              ]}
              dataSource={geospatialDatasets}
              pagination={false}
              size="small"
              rowKey="id"
            />
          </Card>

          <Card title="统计信息">
            <Statistic title="地理空间数据集" value={geospatialDatasets.length} />
            <Statistic
              title="总要素数"
              value={geospatialDatasets.reduce((sum, ds) => sum + (ds.shape?.n_samples || 0), 0)}
              style={{ marginTop: 16 }}
            />
          </Card>
        </Col>
      </Row>

      {/* 上传地理空间数据集模态框 */}
      <Modal
        title="上传地理空间数据集"
        visible={uploadModalVisible}
        onCancel={() => {
          setUploadModalVisible(false);
          form.resetFields();
          setUploadProgress(0);
        }}
        footer={null}
        width={600}
      >
        {uploadProgress > 0 && (
          <div style={{ marginBottom: 16 }}>
            <Progress percent={uploadProgress} status={uploadProgress === 100 ? 'success' : 'active'} />
          </div>
        )}

        <Form
          form={form}
          layout="vertical"
          initialValues={{
            geometry_type: 'point',
            coordinate_system: 'EPSG:4326'
          }}
        >
          <Form.Item
            name="name"
            label="数据集名称"
            rules={[{ required: true, message: '请输入数据集名称' }]}
          >
            <Input placeholder="输入数据集名称" />
          </Form.Item>

          <Form.Item
            name="description"
            label="描述"
          >
            <TextArea rows={3} placeholder="输入数据集描述（可选）" />
          </Form.Item>

          <Form.Item
            name="geometry_type"
            label="几何类型"
          >
            <Select>
              <Option value="point">点 (Point)</Option>
              <Option value="polygon">多边形 (Polygon)</Option>
              <Option value="line">线 (LineString)</Option>
              <Option value="mixed">混合类型</Option>
            </Select>
          </Form.Item>

          <Form.Item
            name="coordinate_system"
            label="坐标系统"
          >
            <Select>
              <Option value="EPSG:4326">WGS84 (EPSG:4326)</Option>
              <Option value="EPSG:3857">Web墨卡托 (EPSG:3857)</Option>
              <Option value="EPSG:4490">CGCS2000 (EPSG:4490)</Option>
            </Select>
          </Form.Item>

          <Form.Item
            name="vectorColumns"
            label="向量列名"
            rules={[{ required: true, message: '请输入向量列名' }]}
          >
            <Select mode="tags" placeholder="输入向量列名，按回车添加" />
          </Form.Item>

          <Form.Item label="数据文件">
            <Dragger
              name="file"
              multiple={false}
              beforeUpload={handleUpload}
              showUploadList={false}
              disabled={uploadingFile}
              accept=".shp,.geojson,.gdb,.gpkg,.zip"
            >
              <p className="ant-upload-drag-icon">
                <UploadOutlined />
              </p>
              <p className="ant-upload-text">点击或拖拽文件到此区域上传</p>
              <p className="ant-upload-hint">支持 Shapefile、GeoJSON、GDB、GeoPackage 等格式</p>
            </Dragger>
          </Form.Item>
        </Form>
      </Modal>
    </div>
  );
};

// 地理空间分析结果组件
const SpatialClusteringResult: React.FC<{ result: AnalysisResult }> = ({ result }) => (
  <div>
    <Row gutter={[16, 16]}>
      <Col span={8}>
        <Card title="空间聚类信息">
          <Statistic title="聚类数量" value={result.result.n_clusters} />
          <Statistic
            title="空间度量指标"
            value={result.result.spatial_metrics ? '已包含' : '未包含'}
            style={{ marginTop: 16 }}
          />
        </Card>
      </Col>
      <Col span={16}>
        <Card title="空间聚类分布">
          <ReactECharts
            option={{
              title: { text: '空间聚类样本分布' },
              tooltip: { trigger: 'axis' },
              xAxis: {
                type: 'category',
                data: result.result.cluster_counts?.map((c: any) => `空间聚类 ${c.cluster + 1}`) || []
              },
              yAxis: { type: 'value' },
              series: [{
                type: 'bar',
                data: result.result.cluster_counts?.map((c: any) => c.count) || [],
                itemStyle: { color: '#1890ff' }
              }]
            }}
            style={{ height: '300px' }}
          />
        </Card>
      </Col>
    </Row>
  </div>
);

const SpatialSimilarityResult: React.FC<{ result: AnalysisResult }> = ({ result }) => (
  <Card title="空间相似度分析结果">
    <Row gutter={[16, 16]}>
      <Col span={6}>
        <Statistic title="空间权重" value={result.result.spatial_weight} />
      </Col>
      <Col span={6}>
        <Statistic title="特征权重" value={result.result.feature_weight} />
      </Col>
      <Col span={6}>
        <Statistic title="相似对数" value={result.result.n_pairs || 0} />
      </Col>
      <Col span={6}>
        <Statistic title="平均相似度" value={result.result.avg_similarity || 0} precision={3} />
      </Col>
    </Row>
  </Card>
);

const GeospatialStatisticsResult: React.FC<{ result: AnalysisResult }> = ({ result }) => (
  <Card title="地理空间统计分析结果">
    <Row gutter={[16, 16]}>
      <Col span={8}>
        <Statistic title="样本数量" value={result.result.n_samples || 0} />
      </Col>
      <Col span={8}>
        <Statistic title="向量维度" value={result.result.vector_size || 0} />
      </Col>
      <Col span={8}>
        <Statistic title="数据类型" value={result.result.data_type || '未知'} />
      </Col>
    </Row>
    <Divider />
    <Row gutter={[16, 16]}>
      <Col span={12}>
        <Card size="small" title="空间相关性">
          <p>XY 相关系数: {result.result.spatial_correlation?.xy_correlation?.toFixed(3) || 'N/A'}</p>
        </Card>
      </Col>
      <Col span={12}>
        <Card size="small" title="空间自相关">
          <p>平均邻居距离: {result.result.spatial_autocorrelation?.avg_neighbor_distance?.toFixed(3) || 'N/A'}</p>
        </Card>
      </Col>
    </Row>
  </Card>
);

export default GeospatialAnalysis;